package com.trs.publish.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author jiahaihong
 *
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	
	@Autowired  
	private CustomUserDetailsService customUserDetailsService;
	
	
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http.csrf().disable();
         http.authorizeRequests()
         		 .antMatchers("/login").permitAll()//访问：/home 无需登录认证权限  
                 .anyRequest().authenticated() //其他所有资源都需要认证，登陆后访问  
		         .and().formLogin().loginPage("/login")
		         .successHandler(loginSuccessHandler()) //登录成功后可使用loginSuccessHandler()存储用户信息。
		         .failureUrl("/login?error").permitAll() //登录页面用户任意访问
		         .and().logout().logoutSuccessUrl("/login").permitAll() //注销行为任意访问
		         .invalidateHttpSession(true)  //销毁session信息
		         .and().headers().frameOptions().disable();
         http.headers().frameOptions().disable();
    }
    
    @Autowired  
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {     
		//指定密码加密所使用的加密器为passwordEncoder()  
		//需要将密码加密后写入数据库   
    	auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());  
    	//不删除凭据，以便记住用户
    	auth.eraseCredentials(false);         
    }  
  
    @Bean  
    public BCryptPasswordEncoder passwordEncoder() {  
        return new BCryptPasswordEncoder(4);  
    }  
  
    @Bean  
    public LoginSuccessHandler loginSuccessHandler(){  
        return new LoginSuccessHandler();  
    }  
    
    
    //忽略静态资源
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/images/**","/js/**","/css/**");
    }
    
   
  
  


}
